﻿using Microsoft.SharePoint;

namespace PD.ShP.Code
{
    /// <summary>
    /// Extensions for SPGroupCollection member for accessing groups safely.
    /// </summary>
    public static class SPGroupCollectionHelper
    {
        /// <summary>
        /// Gets the sharepoint group by name safe.
        /// </summary>
        /// <param name="collection">The collection of sharepoint groups.</param>
        /// <param name="name">The sharepoint group name.</param>
        /// <returns>
        /// The group on a Windows SharePoint Services Web site if exists; otherwise null;
        /// </returns>
        public static SPGroup GetByNameSafe(this SPGroupCollection collection, string name)
        {
            try
            {
                return collection[name];
            }
            catch (SPException)
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the sharepoint group by id safe.
        /// </summary>
        /// <param name="collection">The collection of sharepoint groups.</param>
        /// <param name="id">The sharepoint group id.</param>
        /// <returns>
        /// The group on a Windows SharePoint Services Web site if exists; otherwise null;
        /// </returns>
        public static SPGroup GetByIdSafe(this SPGroupCollection collection, int id)
        {
            try
            {
                return collection.GetByID(id);
            }
            catch (SPException)
            {
                return null;
            }
        }
    }
}
